package com.doudou.feign;

import com.doudou.commons.entity.Result;
import com.netflix.client.ClientException;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import feign.RetryableException;

import java.lang.reflect.Method;
import java.net.ConnectException;

/**
 * @Author: 傻男人
 * @Date: 2020/5/25 11:28
 * @Version: 1.0
 * @Description: 默认Hystrix失败处理类
 */
public class DefaultHystrixFallbackHandler extends HystrixFallbackHandler {

    public DefaultHystrixFallbackHandler(Class<?> feignClientClass, Throwable cause) {
        super(feignClientClass, cause);
    }

    @Override
    protected Object handle(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> returnType = method.getReturnType();
        Result result = (Result) returnType.newInstance();
        Throwable throwable = getCause();
        result.setCode(1000);
        result.setErrorMsg(throwable.getMessage());
        //ribbon 异常
        if (throwable instanceof RetryableException) {
            Throwable cause = throwable.getCause();
            if (cause != null) {
                result.setMessage(cause instanceof ConnectException ? "ribbon连接超时或者无可用的服务！" : "内部服务出错！");
                return result;
            }
        }

        //无可用服务
        if (throwable instanceof RuntimeException) {
            Throwable cause = throwable.getCause();
            if (cause != null) {
                result.setMessage(cause instanceof ClientException ? "feign 无可用服务！" : "内部服务出错！");
                return result;
            }
        }
        //hystrix 超时
        if (throwable instanceof HystrixTimeoutException) {
            result.setMessage("hystrix 超时！");
            result.setErrorMsg("hystrix time out!");
            return result;
        }
        result.setMessage("内部服务出错！");
        return result;
    }

}


